package com.mes.web.controller.tdd;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.google.gson.Gson;
import com.mes.entity.cb.Order;
import com.mes.entity.cb.OrderDetailed;
import com.mes.entity.tdd.ProcurementChuku;
import com.mes.entity.tdd.ProcurementRuku;
import com.mes.entity.tdd.ProcurementRukuMateriel;
import com.mes.entity.tdd.tj.Tpage;
import com.mes.service.tdd.OthersService;
import com.mes.service.tdd.ProcurementChukuService;
import com.mes.service.tdd.ProcurementRukuMaterielService;
import com.mes.service.tdd.ProcurementRukuService;
import com.mes.utils.DateJsonValueProcessor;
import com.mes.utils.ResponseUtil;
import com.mes.utils.StringUtil;
/**
 * 
 *@ClassName: ProcurementRukuController 
 *@Description: 到货单
 *@Author tdd
 *@Date 2018-6-5 下午3:57:49 
 *@version 1.0
 */
@Controller
@RequestMapping("/procurementRuku")
public class ProcurementRukuController {
	//注入到货单Server
	@Resource public ProcurementRukuService rukuService;
	//注入到货单详情Server
	@Resource public ProcurementRukuMaterielService rukuMaterielService;
	//注入模块所需其他的方法Server
	@Resource private OthersService othersService;
	//注入到货单Server
	@Resource public ProcurementChukuService chukuService;
	/**
	 * 采购到货单分页
	 * @param request request对象
	 * @param pageBean 分页+条件
	 * @param limit 每页条数
	 * @param offset 条数
	 * @param response response对象
	 * @throws Exception 异常
	 */
	@RequestMapping("/list")
	public void materieDemandList(HttpServletRequest request,Tpage pageBean,@RequestParam(value="limit",required=false)String limit,@RequestParam(value="offset",required=false)String offset,HttpServletResponse response) throws Exception {
		
		/*String suppliername = request.getParameter("suppliername"); 
		if(null != suppliername && !suppliername.equals("")){
			suppliername = new String(suppliername.getBytes("iso8859-1"),"utf-8");
			pageBean.setStaffname(suppliername);
		}*/
		//页数
		pageBean.setPage(Integer.parseInt(offset)/Integer.parseInt(limit));
		//每页条数
		pageBean.setPageSize(Integer.parseInt(limit));
		//未删除
		pageBean.setIsdelete("0");
		List<ProcurementRuku> list=rukuService.list(pageBean);
		int total=rukuService.total(pageBean);
		
		JSONObject jsonObject = new JSONObject();
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(java.util.Date.class,new DateJsonValueProcessor("yyyy-MM-dd"));
		JSONArray jsonArray = JSONArray.fromObject(list, jsonConfig);
		jsonObject.put("total", total);
		jsonObject.put("rows", jsonArray);
		ResponseUtil.write(response, jsonObject);
	}
	/**
	 * 查询所有到货单
	 * @param response response对象
	 * @throws Exception 异常
	 */
	@RequestMapping("/all")
	public void all(Tpage pageBean,HttpServletResponse response) throws Exception{
		pageBean.setPage(0);
		pageBean.setPageSize(rukuService.total(pageBean));
		List<ProcurementRuku> list=rukuService.list(pageBean);
		Gson gson = new Gson();
		ResponseUtil.write(response, gson.toJson(list));
	}
	/**
	 * 根据到货单号查到货单
	 * @param pcnum 到货单号
	 * @return 到货单集合
	 */
	public List<ProcurementRuku> findbyprnum(String prnum){
		Tpage pageBean = new Tpage();
		//未删除
		pageBean.setIsdelete("0");
		pageBean.setPrnum(prnum);
		//页数
		pageBean.setPage(0);
		//每页条数
		pageBean.setPageSize(rukuService.total(pageBean));
		List<ProcurementRuku> list=rukuService.list(pageBean);
		return list;
	}
	/**
	 * 根据订单id查 订单+物料
	 * @param porderid 订单id
	 * @return 订单详情集合
	 */
	public List<OrderDetailed> findbyporderid(String porderid){
		OrderDetailed detailed= new OrderDetailed();
		Order order = new Order();
		order.setId(Long.valueOf(porderid));
		detailed.setOrder(order);
		List<OrderDetailed> list = othersService.findbyporderid(detailed);
		return list;
	}
	/**
	 * 到货单添加（弃用）
	 * @param procurementRuku 到货单
	 * @param response  response对象
	 * @throws Exception 异常
	 */
	@RequestMapping("/add1")
	public void materieDemandAdd1(ProcurementRuku procurementRuku,HttpServletResponse response) throws Exception {
		List<ProcurementRuku> findbyprnum = findbyprnum(procurementRuku.getPrnum());
		Gson gson = new Gson();
		Map<String,Object> map=new HashMap<String,Object>();
		if (null != findbyprnum && findbyprnum.size() > 0) {
			map.put("success", "-1");
		}else {
			//未入库
			procurementRuku.setPrstate("0");
			//未被退货单选择
			procurementRuku.setPrremark20("0");
			Long id = rukuService.add(procurementRuku);
			if (null != id && id > 0) {
				/*根据到货单id查 到货单+物料*/
				List<OrderDetailed> findbyporderid = findbyporderid(procurementRuku.getPorderid());
				for (OrderDetailed orderDetailed : findbyporderid) {
					ProcurementRukuMateriel rukuMateriel = new ProcurementRukuMateriel();
					rukuMateriel.setPrid(id);
					rukuMateriel.setMaterielid(orderDetailed.getMaterieid());
					//添加
			    	rukuMaterielService.add(rukuMateriel);
				}
				map.put("success", "1");
				map.put("prid", id);
			}else {
				map.put("success", "0");
			}
		}
		ResponseUtil.write(response, gson.toJson(map));
	}
	/**
	 * 添加
	 * @param procurementRuku 单
	 * @param pmid 详情id
	 * @param pmbatchnumber 批号
	 * @param barcode 条形码
	 * @param materielid 物料id
	 * @param number 数量
	 * @param pmremark2 订单详情id
	 * @param response response对象
	 * @throws Exception 异常
	 */
	@RequestMapping("/add")
	public void materieDemandAdd(ProcurementRuku procurementRuku,String[] pmid,String[] pmbatchnumber,String[] barcode,String[] materielid,String[] number,String[] pmremark2,HttpServletResponse response) throws Exception {
		List<ProcurementRuku> findbyprnum = findbyprnum(procurementRuku.getPrnum());
		Gson gson = new Gson();
		Map<String,Object> map=new HashMap<String,Object>();
		if (null != findbyprnum && findbyprnum.size() > 0) {
			map.put("success", "-1");
		}else {
			//未入库
			procurementRuku.setPrstate("0");
			//未被退货单选择
			procurementRuku.setPrremark20("0");
			Long id = rukuService.add(procurementRuku);
			if (null != id && id > 0) {
				/*添加到货单详情*/
				for (int i = 0; i < pmremark2.length; i++) {
					ProcurementRukuMateriel rukuMateriel = new ProcurementRukuMateriel();
					rukuMateriel.setPrid(id);
					rukuMateriel.setPmbatchnumber(pmbatchnumber[i]);
					rukuMateriel.setBarcode(barcode[i]);
					rukuMateriel.setMaterielid(Long.valueOf(materielid[i]));
					rukuMateriel.setNumber(number[i]);
					rukuMateriel.setPmremark2(pmremark2[i]);
					//添加
					rukuMaterielService.add(rukuMateriel);
				}
				map.put("success", "1");
				map.put("prid", id);
			}else {
				map.put("success", "0");
			}
		}
		ResponseUtil.write(response, gson.toJson(map));
	}
	/**
	 * 去修改到货单
	 * @param model map集合
	 * @param request request对象
	 * @return 跳转tdd/erp/procurementRukuAdd.jsp
	 */
	@RequestMapping("/toupdata")
	public String toupdata(Model model,HttpServletRequest request){
		Tpage pageBean = new Tpage();
		//页数
		pageBean.setPage(0);
		//每页条数
		pageBean.setPageSize(10);
		pageBean.setPrid(Long.valueOf((Integer.parseInt(request.getParameter("prid")))));
		List<ProcurementRuku> list = rukuService.list(pageBean);
		if (list.size()>0) {
			model.addAttribute("ProcurementRuku", list.get(0));
		}
		return "tdd/erp/procurementRukuAdd";
	}
	/**
	 * 修改弃用
	 * @param procurementRuku 到货单
	 * @param response response对象
	 * @throws Exception 异常
	 */
	@RequestMapping("/save1")
	public void materieDemandSave1(ProcurementRuku procurementRuku,HttpServletResponse response) throws Exception {
		Tpage pageBean = new Tpage();
		//页数
		pageBean.setPage(0);
		//每页条数
		pageBean.setPageSize(10);
		pageBean.setPrid(procurementRuku.getPrid());
		List<ProcurementRuku> list = rukuService.list(pageBean);
		Map<String,Object> map=new HashMap<String,Object>();
		Gson gson = new Gson();
		if (list.size() > 0) {
			List<ProcurementRuku> findbyprnum = findbyprnum(procurementRuku.getPrnum());
			if (null != findbyprnum && findbyprnum.size() > 0 && !procurementRuku.getPrid().equals(findbyprnum.get(0).getPrid())) {
				map.put("success", "-1");
			}else {
				int id = rukuService.updata(procurementRuku);
				if (id > 0) {
					map.put("success", "1");
				}else {
					map.put("success", "0");
				}
			}
		//已删除
		} else {
			map.put("success", "2");
		}
		ResponseUtil.write(response, gson.toJson(map));
	}
	/**
	 * 修改
	 * @param procurementRuku 单
	 * @param pmid 详情id
	 * @param pmbatchnumber 批号
	 * @param barcode 条形码
	 * @param materielid 物料id
	 * @param number 数量
	 * @param pmremark2 订单详情id
	 * @param response response对象
	 * @throws Exception 异常
	 */
	@RequestMapping("/save")
	public void materieDemandSave(ProcurementRuku procurementRuku,String[] pmid,String[] pmbatchnumber,String[] barcode,String[] materielid,String[] number,String[] pmremark2,HttpServletResponse response) throws Exception {
		Tpage pageBean = new Tpage();
		//页数
		pageBean.setPage(0);
		//每页条数
		pageBean.setPageSize(10);
		pageBean.setPrid(procurementRuku.getPrid());
		List<ProcurementRuku> list = rukuService.list(pageBean);
		Map<String,Object> map=new HashMap<String,Object>();
		Gson gson = new Gson();
		if (list.size() > 0) {
			List<ProcurementRuku> findbyprnum = findbyprnum(procurementRuku.getPrnum());
			if (null != findbyprnum && findbyprnum.size() > 0 && !procurementRuku.getPrid().equals(findbyprnum.get(0).getPrid())) {
				map.put("success", "-1");
			}else {
				int id = rukuService.updata(procurementRuku);
				if (id > 0) {
					/*添加到货单详情*/
					for (int i = 0; i < pmremark2.length; i++) {
						Tpage pageBean1 = new Tpage();
						//获取id
						pageBean1.setPmid(Long.valueOf(pmid[i]));
						//未删除
						pageBean1.setIsdelete("0");
						List<ProcurementRukuMateriel> list1 = rukuMaterielService.list(pageBean1);
						//如果有该条数据
						if (list.size()>0) {
							ProcurementRukuMateriel rm2 = list1.get(0);
							if( null!= pmbatchnumber[i] && !pmbatchnumber[i].equals("")){
								rm2.setPmbatchnumber(pmbatchnumber[i]);
							}
							if( null!= number[i] && !number[i].equals("")){
								rm2.setNumber(number[i]);
							}
							if( null!= barcode[i] && !barcode[i].equals("")){
								rm2.setBarcode(barcode[i]);
							}
							//修改
							int n = rukuMaterielService.updata(rm2);
						}
					}
					map.put("success", "1");
				}else {
					map.put("success", "0");
				}
			}
			//已删除
		} else {
			map.put("success", "2");
		}
		ResponseUtil.write(response, gson.toJson(map));
	}
	/**
	 * 删除
	 * @param ids 到货单id用","拼接而成的字符串
	 * @param response response对象
	 * @throws Exception 异常
	 */
	@RequestMapping("/delete")
	public void materieDemandDelete(String ids,HttpServletResponse response) throws Exception {
		List<Long> listId = StringUtil.splitListL(ids, ",");
        for (int i = 0; i < listId.size(); i++) {
        	//判断退货单是否使用该到货单
        	Tpage page = new Tpage();
        	//页数
    		page.setPage(0);
    		//每页条数
    		page.setPageSize(10);
    		//未删除
    		page.setIsdelete("0");
    		page.setPrukuid(String.valueOf(listId.get(i)));
    		List<ProcurementChuku> listr=chukuService.list(page);
        	if(listr.size() <= 0){
	        	Tpage pageBean = new Tpage();
				//页数
				pageBean.setPage(0);
				//每页条数
				pageBean.setPageSize(10);
				pageBean.setPrid(listId.get(i));
				List<ProcurementRuku> list = rukuService.list(pageBean);
				if (list.size() > 0) {
					ProcurementRuku procurementRuku = list.get(0);
	        		//是否删除指定删除
	        		//删除（假删除）
	        		int n = rukuService.updatadelete(procurementRuku);
	        		//删除成功
	        		if (n >= 1) {
	        			Tpage  tpage = new Tpage();
	    				tpage.setPrid(listId.get(i));
	    				//页数
	    				pageBean.setPage(0);
	    				//每页条数
	    				pageBean.setPageSize(rukuMaterielService.total(tpage));
	    				List<ProcurementRukuMateriel> listM = rukuMaterielService.list(tpage);
	    				for (ProcurementRukuMateriel rukuMateriel : listM) {
	    					//删除
	    					rukuMaterielService.updatadelete(rukuMateriel);
						}
	        			if (i == (listId.size()-1)) {
	        				response.getWriter().print("1");
						}
	        			//未成功
	        		} else {
	        			response.getWriter().print("0");
	        			break;
	        		}
	        	//如果没有该条数据(没有)
				} else {
					//该数据不存在
	        		response.getWriter().print("2");
	        		break;
				}
			}else{
				response.getWriter().print("-2");
				break;
			}
        }
	}
	
	

	/**
	 * 查询所有到货单
	 * @param response response对象
	 * @throws Exception 异常
	 */
	@RequestMapping("/allprocurementRukuArp")
	public void allArp(HttpServletResponse response) throws Exception{
		Tpage pageBean = new Tpage();
		pageBean.setPage(0);
		pageBean.setPrstate("0");
		pageBean.setPageSize(rukuService.total(pageBean));
		List<ProcurementRuku> list=rukuService.list(pageBean);
		
		//获得数据
		response.setContentType("application/json; charset=utf-8"); 
		net.sf.json.JSONObject jsonObject = new net.sf.json.JSONObject();
		if (list.size()>0) {
			//传递数据到页面
			jsonObject.put("code", "200");
			jsonObject.put("message", "");
			jsonObject.put("results", list);
		}else{
			jsonObject.put("code", "500");
    		jsonObject.put("message", "查询数据为空");
    		jsonObject.put("results", null);
		}
		ResponseUtil.write(response, jsonObject);
	}
	/**
	 * 根据到货单查详情
	 * @param response response对象
	 * @throws Exception 异常
	 */
	@RequestMapping("/findProcurementRukuMaterielByPrid")
	public void allArp(Long prid,HttpServletResponse response) throws Exception{
		Tpage pageBean = new Tpage();
		pageBean.setPage(0);
		pageBean.setIsdelete("0");
		pageBean.setPrid(prid);
		pageBean.setPageSize(rukuMaterielService.total(pageBean));
		//未删除
		List<ProcurementRukuMateriel> list = rukuMaterielService.list(pageBean);
		//获得数据
		response.setContentType("application/json; charset=utf-8"); 
		net.sf.json.JSONObject jsonObject = new net.sf.json.JSONObject();
		if (list.size()>0) {
			//传递数据到页面
			jsonObject.put("code", "200");
			jsonObject.put("message", "");
			jsonObject.put("results", list);
		}else{
			jsonObject.put("code", "500");
    		jsonObject.put("message", "查询数据为空");
    		jsonObject.put("results", null);
		}
		ResponseUtil.write(response, jsonObject);
	}
	
}
